from flask import Blueprint,request,json,jsonify
from db import db1
import os
import requests
import datetime
bp_course=Blueprint('course',__name__)
@bp_course.route('/test',methods=['POST','GET','PUT','DELETE'])
def test():
    if request.method=='POST':
        data=request.data
        if data:
            data=json.loads(data)
        else:
            data=request.form
        sql="insert into test values(0,%d,'%s','%s','%s',%d)"%(int(data['total']),data['name'],data['start'],data['end'],int(data['state']))
        db1.insert(sql)
        return 'ok'
    elif request.method=='DELETE':
        id=request.args.get('id')
        sql="delete from test where id =%d"%(int(id))
        res=db1.insert(sql)
        return jsonify({'code':200})
    elif request.method=='PUT':
        data=request.data
        if data:
            data=json.loads(data)
        else:
            data=request.form
        sql="update test set total=%d,name='%s',starttime='%s',endtime='%s',state=%d where id=%d"%(int(data['total']),data['name'],data['start'],data['end'],int(data['state']),int(data['id']))
        res=db1.insert(sql)
        return jsonify({'code':200})
    else:
        id=request.args.get('id')
        sql="select * from test where id =%d"%(int(id))
        res=db1.find(sql)
        return jsonify({'code':200,'test':res})

from utils.myfile import myfile
@bp_course.route('/upload',methods=['POST'])
def upload():
    file=request.files['file']
    myfile.file_mkdir(2)
    file.save(os.path.join('./static/upload/2',file.filename))
    return 'ok'

@bp_course.route('/scenic',methods=['POST','GET'])
def scenic():
    if request.method=='POST':
        data=request.data
        if data:
            data=json.loads(data)
        else:
            data=request.form
        print(data)
        sql="insert into scenic(title,price,typeid) values('%s',%.2f,%d)"%(data['title'],float(data['price']),int(data['typeid']))
        db1.insert(sql)
        print(sql)
        print('添加成功')
        sql1="select id from scenic where title='%s'"%(data['title'])
        res=db1.find(sql1)
        file=request.files['file']
        myfile.file_mkdir(str(res['id']))
        file.save(os.path.join('./static/upload/'+str(res['id']),file.filename))
        sql2="update scenic set pic='%s' where id=%d"%('/static/upload/'+str(res['id']+"/"+file.filename),int(res['id']))
        db1.insert(sql2)
        return jsonify({'code':200})
    else:
        sql="select * from scenic"
        res=db1.find(sql)
        return jsonify({'code':200,'list':res})

@bp_course.route('cate')
def cate():
    sql="select * from yptype"
    res=db1.findall(sql)
    return jsonify({'code':200,'list':res})

@bp_course.route('record')
def record():
    id=request.args.get('typeid')
    if id=='0':
        sql="select * from record"
    else:
        sql="select * from record where id=%d"%(int(id))
    res=db1.findall(sql)
    list=[]
    for i in res:
        dict={'id':i['id'],'stime':datetime.datetime.strftime(i['stime'],'%Y-%m-%d'),'etime':datetime.datetime.strftime(i['etime'],'%Y-%m-%d'),'money':float(i['money'])}
        list.append(dict)
    return jsonify({'code':200,'list':list})

@bp_course.route('order',methods=['GET','PUT'])
def order():
    if request.method=='PUT':
        id=request.args.get('id')
        sql="select * from orders where id=%d"%(int(id))
        res=db1.find(sql)
        status=2
        if int(res['status'])==2:
            status=1
        sql1="update orders set status=%d where id=%d"%(status,int(id))
        db1.insert(sql1)
        return jsonify({"code":200})
    else:
        page=int(request.args.get('page'))
        page_size=int(request.args.get('page_size'))
        start=(page-1)*page_size
        sql="select * from orders limit %d,%d"%(start,page_size)
        res=db1.findall(sql)
        sql1="select count(id) from orders"
        res1=db1.find(sql1)
        return jsonify({'code':200,'list':res,'total':res1['count(id)']})

@bp_course.route('detail',methods=['POST'])
def detail():
    data=request.data
    if data:
        data=json.loads(data)
    else:
        data=request.form
    sql="insert into goods(name,price,count,order_id) values('%s',%.2f,%d,%d)"%(data['name'],float(data['price']),int(data['count']),int(data['order_id']))
    db1.insert(sql)
    return jsonify({'code':200})

@bp_course.route('homework1',methods=['POST','GET','PUT','DELETE'])
def homework1():
    if request.method=='POST':
        data=request.data
        if data:
            data=json.loads(data)
        else:
            data=request.form
        sql="insert into cate(name) values('%s')"%(data['name'])
        db1.insert(sql)
        return jsonify({'code':200})
    elif request.method=='DELETE':
        id=int(request.args.get('id'))
        sql="delete from cate where id=%d"%(id)
        db1.delete(sql)
        return jsonify({'code':200})
    elif request.method=='PUT':
        # data=request.data
        # if data:
        #     data=json.loads(data)
        # else:
        #     data=request.form
        id=int(request.args.get('id'))
        # sql1="update cate set name=%s"%(data['name'])
        # res=db1.update(sql1)
        sql="select * from cate where id=%d"%(id)
        res=db1.find(sql)
        return jsonify({'code': 200,'list':res})
    else:
        sql="select * from cate"
        res=db1.findall(sql)
        return jsonify({'code':200,'list':res})

@bp_course.route('sendmoney')
def sendmoney():
    money=request.args.get('money')
    if not money:
        return jsonify({'code':201,'mes':'请输入金额'})
    else:
        try:
            money=float(money)
        except:
            return jsonify({'code':202,'mes':'请输入正确格式'})
    if money<0.01:
        return jsonify({'code':203,'mes':'红包金额最小为0.01'})
    elif money>200:
        return jsonify({'code':204,'mes':'红包金额最大为200'})
    else:
        return jsonify({'code': 200,'mes':'格式正确！金额大小符合要求！'})

